package logic

import (
	"context"
	"errors"
	"login-api/cache"
	"login-api/models"

	"login-api/loginrpc/internal/svc"
	"login-api/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if result2 == "" {
		return nil, errors.New("图形验证码错误,请重新输入")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	var user models.User

	if err := user.UserFindById(models.DB, user.ID); err != nil {
		return nil, errors.New("用户不存在")
	}

	if err := user.UserAdd(models.DB); err != nil {
		return nil, err
	}

	return &loginrpc.LoginResponse{}, nil
}
